import { createRouter, createWebHistory } from 'vue-router'
import NewShopLoginView from '../views/NewShopLoginView.vue'
import NewShopRegisterView from '../views/NewShopRegisterView.vue'
import NewShopHomeView from '../views/NewShopHomeView.vue'
import NewShopProductDetailView from '../views/NewShopProductDetailView.vue'
import NewShopCheckoutView from '../views/NewShopCheckoutView.vue'
import NewShopSuccessView from '../views/NewShopSuccessView.vue'
import NewShopAuthService from '../services/NewShopAuthService.js'

// 创建新的路由实例
const newShopRouter = createRouter({
  history: createWebHistory('/'),
  routes: [
    {
      path: '/new-shop-login',
      name: 'NewShopLogin',
      component: NewShopLoginView,
      meta: {
        requiresGuest: true // 需要未登录状态才能访问
      }
    },
    {
      path: '/new-shop-register',
      name: 'NewShopRegister',
      component: NewShopRegisterView,
      meta: {
        requiresGuest: true // 需要未登录状态才能访问
      }
    },
    {
      path: '/new-shop',
      name: 'NewShopHome',
      component: NewShopHomeView,
      meta: {
        requiresAuth: true // 需要登录状态才能访问
      }
    },
    {
      path: '/new-shop/product/:id',
      name: 'NewShopProductDetail',
      component: NewShopProductDetailView,
      meta: {
        requiresAuth: true // 需要登录状态才能访问
      },
      props: true
    },
    {
      path: '/new-shop/checkout',
      name: 'NewShopCheckout',
      component: NewShopCheckoutView,
      meta: {
        requiresAuth: true // 需要登录状态才能访问
      }
    },
    {
      path: '/new-shop/order-success',
      name: 'NewShopSuccess',
      component: NewShopSuccessView,
      meta: {
        requiresAuth: true // 需要登录状态才能访问
      }
    },
    // 重定向到登录页面
    {
      path: '/new-shop/*',
      redirect: '/new-shop-login'
    }
  ]
})

// 添加路由守卫
newShopRouter.beforeEach((to, from, next) => {
  // 检查是否需要登录
  if (to.meta.requiresAuth) {
    if (!NewShopAuthService.isLoggedIn()) {
      // 如果未登录，则重定向到登录页面
      next({
        path: '/new-shop-login',
        query: { redirect: to.fullPath }
      })
      return
    }
  }
  
  // 检查是否需要未登录
  if (to.meta.requiresGuest) {
    if (NewShopAuthService.isLoggedIn()) {
      // 如果已登录，则重定向到首页
      next({
        path: '/new-shop'
      })
      return
    }
  }
  
  // 正常继续
  next()
})

export default newShopRouter